<?php
/**
 * @Author: EYong
 * @Date:   2018-04-27 14:05:59
 * @Last Modified by:   EYong
 * @Last Modified time: 2019-05-17 10:05:15
 */
namespace app\admin\controller;
use app\admin\model\Adminuser;
use app\admin\model\Channel as ChannelModel;
use app\admin\model\ChannelCmpp as ChannelCmppModel;
use app\admin\model\Channelip as ChannelIpModel;
use app\admin\model\Channelkey as ChannelkeyModel;
use app\admin\model\ChannelName as ChannelNameModel;
use think\Controller;
use think\Db;

class Channel extends Father {
	//渠道主页
	public function index() {
		$usertype = session('user_type');

		if (input('get.api')) {

			$request    = input('get.');
			$channel_id = isset($request['cid']) ? trim($request['cid']) : '';

			$model = new ChannelModel();

			//查询渠道用户对应的所有子渠道
			$channel_id_arr = $model->getChannelTree(session('relate_id'));
			$where[]        = ['bc.channel_id', 'in', $channel_id_arr];
			$field          = [
				'bc.channel_id'
				, 'bc.company_name'
				, 'bc.currency'
				, 'bc.user_name'
				, 'bc.channel_phone'
				, 'bc.status'
				, 'bc.create_time'
				, 'bc.src_id'
				, 'bc.range_size'
				, 'bc.overdraft_limit'
				, 'bc.level'
				, 'bc.channel_type'
				, 'bc.back_url'
				, 'key.cid_key',
			];

			if (!empty($channel_id)) {

				$where[] = ['bc.channel_id', '=', $channel_id];
			}

			$data = $model->getAll($request, $field, $where);

			$count = $data->total();

			$list = $data->toArray();

			$list = $list['data'];

			return json(['code' => 0, 'msg' => '', 'count' => $count, 'data' => $list]);

		} else {

			if ($usertype == 'admin') {

				$channel_info = ChannelModel::withSearch(['off_redis'])->field('channel_id,company_name')->select();
			} else {

				//查询渠道用户对应的所有子渠道
				$channel_info = ChannelModel::withSearch(['off_redis'])->where(['p_id' => session('relate_id')])->select();
			}

			$this->assign('chas', $channel_info);
			return $this->fetch();
		}
	}

	//编辑渠道
	public function edt() {
		$keyModel = new ChannelkeyModel();

		if (request()->isPost()) {
			//接参
			$data       = request()->post(false);
			$updatedata = request()->only([
				'back_url',
				'company_name',
			]);
			//回调地址
			$data['back_url'] = urldecode($updatedata['back_url']);

			//新增扩展位
			// if (isset($data['range_size'])) {

			// 	$rangeSize = trim($data['range_size']);
			// }

			// channel数据验证
			$validate = validate('Channel');

			//渠道更新子渠道信息
			if (!$validate->scene('channel_edt')->check($updatedata)) {

				return json(['code' => 1, 'msg' => $validate->getError()]);
			}

			//更新渠道用户信息
			$channelModel = new ChannelModel();
			if ($channelModel->where(['channel_id' => $data['cid'], 'p_id' => session('relate_id')])->update($updatedata)) {
				return json(['code' => 0, 'msg' => '更新完成']);
			} else {
				return json(['code' => 1, 'msg' => '更新渠道信息失败！请重试']);

			}
		} else {

			// 请求页面
			$channelId = trim(input('get.id'));

			if (!is_numeric($channelId)) {

				return json(['code' => 1, 'msg' => '参数错误！~请重试']);
			}

			//获取key
			// $keyInfo = $keyModel->getKeyArr($channelId);
			// $this->assign('cid_key', $keyModel->where('cid', $channelId)->value('cid_key'));
			$this->assign('cid_key', '');
			//获取渠道信息
			$channelModel = new ChannelModel();

			$channelInfo = $channelModel->field('bus_channel.*')
				->where(['bus_channel.channel_id' => $channelId])
				->where(['bus_channel.p_id' => session('relate_id')])
				->find();

			$this->assign('info', $channelInfo);
			//这些参数数字大的传到前端会转成科学计算法。。。。
			// $this->assign('src_id', $channel_cmpp_info['src_id']);
			$this->assign('channel_phone', $channelInfo['channel_phone']);

			$this->assign('main_review_mode', Db::table('main_review_mode')->field('id,desc')->select());
			return $this->fetch();
		}
	}

	//开启与关闭
	public function openClose() {
		if ($this->request->isPost()) {

			$channelModel = new ChannelModel();
			$data         = $this->request->post();
			$channel_id   = trim($data['channel_id']);
			$status       = trim($data['status']);

			if ($status == '1') {

				$result = $channelModel->openOrClose($channel_id, '1');
			} else {

				$result = $channelModel->openOrClose($channel_id, '0');
			}

			deleteCache('CHANNEL');
			return $result;
		}
	}

	/**
	 * 添加子渠道
	 */
	public function addChild() {
		$channelId = session('relate_id'); //渠道id
		if ($this->request->isPost()) {

			$data = $this->request->post();

			//重复名字
			if (ChannelModel::where('company_name', trim($data['company_name']))->where('p_id', $channelId)->find()) {
				return json([
					'code' => 1,
					'msg'  => '已创建相同的公司名称',
				]);
			}

			//生成渠道号
			$childId = ChannelModel::withTrashed()->max('channel_id') + 1;
			//接入码
			$srcId = ChannelModel::withTrashed()->max('src_id') + 1;
			//查询本渠道
			$channel = ChannelModel::field('range_size,level,agent_id,currency,sm_type')->where(['channel_id' => $channelId])->find();
			halt($channel);

			if (!in_array($channel['level'], [1, 2, 4])) {
				return json([
					'code' => 1,
					'msg'  => '权限不足',
				]);
			}

			$level = $channel['level'] + 1;

			//数据处理
			$newData = [
				'channel_id'    => $childId,
				'company_name'  => trim($data['company_name']),
				'user_name'     => trim($data['user_name']),
				'channel_phone' => trim($data['channel_phone']),
				'ip'            => trim($data['ip']),
				'channel_type'  => trim($data['channel_type']),
				'agent_id'      => $channel['agent_id'],
				'p_id'          => $channelId, //上级渠道id
				'off_ip'        => trim($data['off_ip']),
				'back_url'      => trim(stripslashes($data['back_url'])),
				'level'         => $level,
				'src_id'        => $srcId,
				'range_size'    => $channel['range_size'],
				'currency'      => $channel['currency'],
				'sm_type'       => $channel['sm_type'],
			];
			$validate = validate('Channel');
			if (!$validate->scene('add')->check($newData)) {
				$result = [
					'code' => 1,
					'msg'  => $validate->getError(),
				];
				return json($result);
			}

			if ($data['off_ip'] == 0) {
				//检测ip是否正确
				if ($this->checkIp(trim($data['ip'])) == false) {
					$result = [
						'code' => 1,
						'msg'  => 'ip格式错误',
					];
					return json($result);
				}
			}

			// 如果是CMPP账号类型
			if ($data['channel_type'] == 'CMPP') {

				// $cmpp_data = [
				// 	'channel_id' => $childId,
				// 	'sp_id'      => Db::table('bus_channel_cmpp')->max('sp_id') + 1,
				// 	'sp_pwd'     => $data['sp_pwd'],
				// 	'reg_id'     => 2,
				// 	'ip'         => '172.18.183.168',
				// 	'port'       => 7890,
				// 	'sms_limit'  => 50,
				// 	'onoff'      => $data['onoff'],
				// 	'time'       => date('Y-m-d H:i:s', time()),
				// ];
				// $cmpp_service_data = Db::table('bus_cmpp_server_reg_center')->where('id', $cmpp_data['reg_id'])->find();
			}

			// 启动事务
			Db::startTrans();
			try {
				//检测并且添加渠道ip白名单
				$channelModel = new ChannelModel();
				$channelModel->checkIp(trim($data['ip']), $childId);

				//添加渠道key
				$keyModel = new ChannelkeyModel();
				$keyModel->addKey($childId);
				//添加渠道信息
				$channelModel->addChannel($newData);

				$result = [
					'code' => 0,
					'msg'  => $childId,
				];
				// 如果是cmpp账号类型，添加channel_cmpp数据，添加CMPP服务器的ip到ip白名单
				if ($data['channel_type'] == 'CMPP') {

					Db::table('bus_channel_cmpp')->insert($cmpp_data);
					$channelModel->checkIp(trim($cmpp_service_data['ip']), $channelId);
				}

				$channelNameModel = new ChannelNameModel();
				$channelNameModel->add(['cid' => $newData['channel_id'], 'cname' => $newData['company_name']]);

				// 提交事务
				Db::commit();

				deleteCache('CHANNEL');

				return json($result);
			} catch (\Exception $e) {
				trace($e->getMessage(), 'error');
				// 回滚事务
				Db::rollback();
				$result = [
					'code' => 1,
					'msg'  => '添加失败，请重试！',
				];
				return json($result);
			}
		}
		return $this->fetch();
	}

	//检测ip
	public function checkIp($ip) {
		$ip      = str_replace('，', ',', $ip);
		$ip      = explode(',', $ip);
		$pattern = "/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/";
		foreach ($ip as $k => $v) {
			if (!preg_match($pattern, $v)) {
				return false;
			}
		}
		return true;
	}

	//渠道添加用户页面
	public function user() {
		if (input('get.api')) {
			$request = input('get.');
			//实例化Adminuser类
			$user_m = new Adminuser;

			//查询处理数据
			$data = $user_m
				->alias('us')
				->field('us.*,ro.role_id,ro.role_name,cha.channel_id,cha.company_name,pla.id as plat_id,pla.platfrom')
				->join('adm_role ro', ' us.role_id = ro.role_id', 'LEFT')
				->join('bus_channel cha', ' us.relate_id = cha.channel_id', 'LEFT')
				->join('bus_platfrom pla', ' us.relate_id = pla.plat_id', 'LEFT')
				->where('cha.p_id', session('relate_id'))
				->order('user_type')
				->paginate($request['limit'], false, $request)
				->each(function ($item, $key) {
					//处理数据关联账户
					switch ($item->user_type) {
					case 'channel':
						$item->on_name = $item->company_name;
						break;
					case 'plat':
						$item->on_name = $item->platfrom;
						break;

					default:
						$item->on_name = '';
						break;
					}
					//处理数据on_off
					switch ($item->on_off) {
					case '1':
						$item->on_off_ = '<span class="layui-badge layui-bg-green status-qy">已开启</span>';
						break;
					case '0':
						$item->on_off_ = '<span class="layui-badge status-jy">已禁用</span>';
						break;
					default:
						$item->on_off_ = '<span class="layui-badge layui-bg-gray status-pz">未配置</span>';
						break;
					}
					//处理数据type
					switch ($item->user_type) {
					case 'admin':
						$item->user_type = '管理员';
						break;
					case 'channel':
						$item->user_type = '渠道';
						break;
					case 'plat':
						$item->user_type = '通道';
						break;
					default:
						$item->user_type = '未知';
						break;
					}

				});

			$count = $data->total();

			$list = $data->toArray();

			$list = $list['data'];

			return json(['code' => 0, 'msg' => '', 'count' => $count, 'data' => $list]);

		} else {

			return $this->fetch();
		}
	}

	//渠道添加登录用户
	public function addUser() {
		if ($this->request->isPost()) {
			//实例化Adminuser类
			$model = new Adminuser;
			$data  = input('post.');
			$preg  = "/^[a-zA-Z0-9_-]{4,16}$/";

			if (!preg_match($preg, $data['admin_name'])) {

				return '用户名不能含有汉字,特殊字符等,长度必须位于4~16位之间';
			}

			$res = $model->channelAdd($data);

			deleteCache('CHANNEL');

			switch ($res) {

			case '1':
				trace(session('username') . '添加用户' . $data['admin_name'], 'info');
				return json(['code' => 0, 'msg' => '新增成功']);
				break;

			case '2':
				return json(['code' => 1, 'msg' => '用户存在！']);
				break;

			default:
				return json(['code' => 1, 'msg' => '添加失败！']);
				break;
			}

		} else {

			$this->assign('channel', db('bus_channel')->field('channel_id,company_name')->where('p_id', session('relate_id'))->select());
			return $this->fetch();
		}
	}

	//渠道登录用户编辑
	public function userEdit() {
		if ($this->request->isPost()) {

			$data = input("post.");

			if ($data['usid']) {

				$user = Adminuser::get($data['usid']);

				$username = $user->username;

				$user->relate_id = trim($data['admin_relate']);

				$user->mark_up = trim($data['mark']);

				if ($user->isUpdate(true)->save() !== false) {

					deleteCache('CHANNEL');
					trace(session('username') . '编辑用户' . $username, 'info');
					return json(['code' => 0, 'msg' => '编辑成功']);
				} else {

					return json(['code' => 1, 'msg' => '编辑失败']);
				}
			}

		} else {

			$userid   = trim(input('get.usid'));
			$userInfo = Adminuser::get(['id' => $userid]);

			if ($userid) {

				$this->assign('usid', $userid);
				$this->assign('list', $userInfo);
				$this->assign('channel', db('bus_channel')->field('channel_id,company_name')->where('p_id', session('relate_id'))->select());
				return $this->fetch();
			} else {

				return '找不到用户！';
			}
		}
	}

	// 刷新cmpp
	// 根据cid获取cmpp ip
	// 根据cmpp reg_id获取服务器接口
	// 请求接口查看相应cid状态
	// 返回状态到前端
	public function query_service() {
		$channel_id = trim(input('post.channelid'));

		if (!is_numeric($channel_id)) {

			return json(['code' => 0, 'msg' => '请求参数错误']);
		}

		$channel_cmpp_data = db('bus_channel_cmpp')
			->where('sp_id', '=', $channel_id)
			->find();

		if (!$channel_cmpp_data) {

			return json(['code' => 0, 'msg' => '请求参数错误']);
		}

		$cmpp_service_data = Db::table('bus_cmpp_server_reg_center')->where('id', $channel_cmpp_data['reg_id'])->find();

		if (!$cmpp_service_data) {

			return json(['code' => 0, 'msg' => '请求服务器不存在']);
		}

		$post_result = curl_post($cmpp_service_data['http_qurey']);

		trace('渠道管理刷新CMPP状态返回json： ' . json_encode($post_result, JSON_UNESCAPED_UNICODE), 'info');

		if ($post_result['code'] == 200) {

			$list           = array_column($post_result['data'], 'spid');
			$search_plat_id = in_array($channel_id, $list);

			if ($search_plat_id) {

				foreach ($post_result['data'] as $key => $value) {

					if ($value['spid'] == $channel_id) {

						if ($value['status']) {

							$status = 1;
						} else {

							$status = 0;
						}

						// 更新CMPP状态
						db('bus_channel_cmpp')
							->where('sp_id', $channel_id)
							->setField('cmpp_status', $status);

						return json(['code' => 1, 'msg' => '', 'status' => $status]);
					}
				}
			} else {

				db('bus_channel_cmpp')
					->where('sp_id', $channel_id)
					->setField('cmpp_status', 0);
			}

			// 更新CMPP状态

			return json(['code' => 1, 'msg' => '未连接', 'status' => 0]);
		} else {

			return json(['code' => 0, 'msg' => '请求接口错误： ' . $post_result['message']]);
		}
	}

	public function test() {
		$a = db('bus_channel')->where('src_id', '')->select();
		halt($a);
		$channelId = ChannelModel::withTrashed()->max('src_id') + 1;
		halt($channelId);
	}

	// 添加编辑请求接口逻辑
	private function interface_operation_request($data, $type = 'add', $channel_type = '') {
		switch ($type) {

		case 'add': // 添加，只有cmpp账号类型会进入这里

			switch ($data['onoff']) {
			// cmpp是否开启

			case 1: // 开启，cmpp ip加入接口白名单

				$cmpp_service_data = db('bus_cmpp_server_reg_center')->where('id', '=', $data['reg_id'])->find();

				$request_result = curl_post1($cmpp_service_data['http_addip'], ['ip' => $data['cmpp_ip']]);

				if ($request_result['code'] == 0) {

					trace('添加渠道成功' . json_encode($request_result, JSON_UNESCAPED_UNICODE), 'info');
					return ['code' => 0, 'msg' => '添加渠道成功'];
				} else {

					trace('添加渠道成功，服务端添加ip白名单失败' . json_encode($request_result, JSON_UNESCAPED_UNICODE), 'info');
					return ['msg' => '添加渠道成功，服务端添加ip白名单失败'];
				}
				break;

			default:
				return ['code' => 0, 'msg' => '添加渠道成功'];
				break;
			}
			break;

		default: // 编辑

			switch ($data['channel_type']) {

			case 'HTTP':

				// 原渠道帐号类型由cmpp->http类型，不需要保存cmpp信息，获取cmpp数据，判断开关状态，删除接口ip白名单
				if ($channel_type != $data['channel_type']) {

					// 渠道cmpp表信息
					$channel_cmpp_data = db('bus_channel_cmpp')
						->where('channel_id', '=', $data['cid'])
						->find();

					// ip请求接口信息
					$cmpp_service_data = db('bus_cmpp_server_reg_center')
						->where('id', '=', $channel_cmpp_data['reg_id'])
						->find();

					Db::startTrans();

					try {

						// db('bus_channel_ip')->where('channel_id','=', $data['cid'])->delete(); // 移除ip表记录

						// 关闭channel_cmpp
						if ($channel_cmpp_data && $channel_cmpp_data['onoff'] == 1) {

							db('bus_channel_cmpp')->where('channel_id', '=', $data['cid'])->setField('onoff', 0);
						}

						Db::commit();

						// 有cmpp记录且cmpp状态为开启
						if ($channel_cmpp_data && $channel_cmpp_data['onoff'] == 1) {

							// 请求接口关闭cmpp服务器ip
							$request_result = curl_post1($cmpp_service_data['http_deleteip'], ['ip' => $channel_cmpp_data['ip']]);

							if ($request_result['code'] == 0) {

								trace('请求接口移除cmppip(' . $channel_cmpp_data['ip'] . ')成功：' . json_encode($request_result, JSON_UNESCAPED_UNICODE), 'info');
								return ['code' => 0, 'msg' => '渠道信息更新成功'];
							} else {

								trace('请求接口移除cmppip(' . $channel_cmpp_data['ip'] . ')失败：' . json_encode($request_result, JSON_UNESCAPED_UNICODE), 'info');
								return ['code' => 1, 'msg' => '渠道信息更新成功，请求接口移除ip白名单失败'];
							}
						} else {

							return ['code' => 0, 'msg' => '渠道信息更新成功'];
						}

					} catch (\Exception $e) {

						Db::rollback();
						trace("关闭CMPP失败" . $e);

						return ['code' => 1, 'msg' => '渠道信息更新成功，cmpp信息更新失败'];
					}
				} else {
					// 渠道账号类型无变更，一直是http类型，无操作

					return ['code' => 0, 'msg' => 'success'];
				}
				break;

			case 'CMPP':

				$channel_cmpp_model = new ChannelCmppModel();
				$channel_ip_model   = new ChannelIpModel();

				// 渠道cmpp表信息
				$channel_cmpp_data = db('bus_channel_cmpp')
					->where('channel_id', '=', $data['cid'])
					->find();

				// 新ip请求接口信息
				$news_cmpp_service_data = db('bus_cmpp_server_reg_center')
					->where('id', '=', $data['reg_id'])
					->find();

				// 原ip请求接口信息，用于移除ip有变化，且状态为开启的原ip
				$old_cmpp_service_data = db('bus_cmpp_server_reg_center')
					->where('id', '=', $channel_cmpp_data['reg_id'])
					->find();

				// 原渠道账号类型由http->cmpp类型，需要保存cmpp信息，判断cmpp是否有数据，更新或新增
				if ($channel_type != $data['channel_type']) {

					if ($channel_cmpp_data) {
						// 有cmpp记录，之前开关必然是关闭的，只需判断是否开启了cmpp状态

						Db::startTrans();

						try {

							// 更新cmpp记录
							$data['ip'] = $data['cmpp_ip'];
							$channel_cmpp_model->updateDataOne($data, ['channel_id' => $data['cid']]);

							Db::commit();

							// 开启了cmpp状态
							if ($data['onoff'] == 1) {

								$request_result = curl_post1($news_cmpp_service_data['http_addip'], ['ip' => $data['ip']]);

							} else {

								$request_result['code'] = 0;
							}

							if ($request_result['code'] == 0) {

								return ['code' => 0, 'msg' => '渠道信息更新成功'];
							} else {

								return ['code' => 1, 'msg' => '渠道信息更新成功，cmpp信息更新失败'];
							}

						} catch (\Exception $e) {

							Db::rollback();
							trace("渠道信息更新成功，cmpp信息更新失败" . $e);

							return ['code' => 1, 'msg' => '渠道信息更新成功，cmpp信息更新失败'];
						}

					} else {
						// 无cmpp记录，添加cmpp和ip白名单

						Db::startTrans();

						try {

							// 添加cmpp记录
							$data['channel_id'] = $data['cid'];
							$data['ip']         = $data['cmpp_ip'];
							$data['time']       = date('Y-m-d H:i:s', time());
							$channel_cmpp_model->addDataOne($data);

							// 服务器ip加白名单
							$channel_ip_model->addOne([
								'channel_id' => $data['cid'],
								'channel_ip' => $news_cmpp_service_data['ip'],
								'ip_status'  => 1,
							]);

							Db::commit();

							// 开启状态，需要请求接口
							if ($data['onoff'] == 1) {

								// 请求接口加入cmpp服务器ip
								$request_result = curl_post1($news_cmpp_service_data['http_addip'], ['ip' => $data['cmpp_ip']]);

								if ($request_result['code'] == 0) {

									trace('请求接口加入cmppip(' . $channel_cmpp_data['ip'] . ')成功：' . json_encode($request_result, JSON_UNESCAPED_UNICODE), 'info');
									return ['code' => 0, 'msg' => '渠道信息更新成功'];
								} else {

									trace('请求接口加入cmppip(' . $channel_cmpp_data['ip'] . ')失败：' . json_encode($request_result, JSON_UNESCAPED_UNICODE), 'info');
									return ['code' => 1, 'msg' => '渠道信息更新成功，cmpp信息更新失败'];
								}

							} else {

								return ['code' => 0, 'msg' => '渠道信息更新成功'];
							}

						} catch (\Exception $e) {

							Db::rollback();
							trace("渠道信息更新成功，cmpp信息更新失败" . $e);

							return ['code' => 1, 'msg' => '渠道信息更新成功，cmpp信息更新失败'];
						}

					}

				} else {
					// 一直是cmpp类型

					if ($channel_cmpp_data) {
						// 有cmpp记录，判断ip和开关状态有没有变化

						Db::startTrans();

						try {

							// 更新cmpp记录
							$data['ip'] = $data['cmpp_ip'];
							$channel_cmpp_model->updateDataOne($data, ['channel_id' => $data['cid']]);

							Db::commit();

							// ip 有变化
							if ($channel_cmpp_data['ip'] != $data['cmpp_ip']) {

								// 状态有变化
								if ($channel_cmpp_data['onoff'] != $data['onoff']) {

									// 之前禁用，现在开启了
									if ($data['onoff'] == 1) {

										$request_result = curl_post1($news_cmpp_service_data['http_addip'], ['ip' => $data['cmpp_ip']]);
										trace('请求加入接口返回信息(' . $data['cmpp_ip'] . ')：' . json_encode($request_result, JSON_UNESCAPED_UNICODE), 'info');
									} else {
										// 之前开启的，现在禁用了

										$request_result = curl_post1($old_cmpp_service_data['http_deleteip'], ['ip' => $channel_cmpp_data['ip']]);
										trace('请求移除接口返回信息(' . $channel_cmpp_data['ip'] . ')：' . json_encode($request_result, JSON_UNESCAPED_UNICODE), 'info');
									}

								} else {

									// 一直开启
									if ($data['onoff'] == 1) {
										// 加入新的ip，移除原来的ip

										$request_result  = curl_post1($news_cmpp_service_data['http_addip'], ['ip' => $data['cmpp_ip']]);
										$request_result1 = curl_post1($old_cmpp_service_data['http_deleteip'], ['ip' => $channel_cmpp_data['ip']]);
										trace('请求加入接口返回信息(' . $data['cmpp_ip'] . ')：' . json_encode($request_result, JSON_UNESCAPED_UNICODE), 'info');
										trace('请求移除接口返回信息(' . $channel_cmpp_data['ip'] . ')：' . json_encode($request_result1, JSON_UNESCAPED_UNICODE), 'info');
									} else {
										// 一直禁用，无操作

										$request_result['code'] = 0;
									}
								}
							} else {
								// ip没有变化

								// 状态有变化
								if ($channel_cmpp_data['onoff'] != $data['onoff']) {

									// 之前禁用，现在开启了
									if ($data['onoff'] == 1) {

										$request_result = curl_post1($news_cmpp_service_data['http_addip'], ['ip' => $channel_cmpp_data['ip']]);
										trace('请求加入接口返回信息(' . $channel_cmpp_data['ip'] . ')：' . json_encode($request_result, JSON_UNESCAPED_UNICODE), 'info');
									} else {
										// 之前开启的，现在禁用了

										$request_result = curl_post1($news_cmpp_service_data['http_deleteip'], ['ip' => $channel_cmpp_data['ip']]);
										trace('请求移除接口返回信息(' . $channel_cmpp_data['ip'] . ')：' . json_encode($request_result, JSON_UNESCAPED_UNICODE), 'info');
									}

								} else {
									// 状态无变化

									$request_result['code'] = 0;
								}
							}

							if ($request_result['code'] == 0) {

								return ['code' => 0, 'msg' => '渠道信息更新成功'];
							} else {

								return ['code' => 1, 'msg' => '渠道信息更新成功，cmpp信息更新失败'];
							}

						} catch (\Exception $e) {

							Db::rollback();
							trace("渠道信息更新成功，cmpp信息更新失败" . $e);

							return ['code' => 1, 'msg' => '渠道信息更新成功，cmpp信息更新失败'];
						}

					} else {
						// 无cmpp记录，怪异处理，添加cmpp和ip白名单

						Db::startTrans();

						try {

							// 添加cmpp记录
							$data['channel_id'] = $data['cid'];
							$data['time']       = date('Y-m-d H:i:s', time());
							$channel_cmpp_model->addDataOne($data);

							// 服务器ip加白名单
							$channel_ip_model->addOne([
								'channel_id' => $data['cid'],
								'channel_ip' => $news_cmpp_service_data['ip'],
								'ip_status'  => 1,
							]);

							Db::commit();

							// 开启状态，需要请求接口
							if ($data['onoff'] == 1) {

								// 请求接口加入cmpp服务器ip
								$request_result = curl_post1($news_cmpp_service_data['http_addip'], ['ip' => $data['cmpp_ip']]);

								if ($request_result['code'] == 0) {

									trace('请求接口加入cmppip(' . $channel_cmpp_data['ip'] . ')成功：' . json_encode($request_result, JSON_UNESCAPED_UNICODE), 'info');
									return ['code' => 0, 'msg' => '渠道信息更新成功'];
								} else {

									trace('请求接口加入cmppip(' . $channel_cmpp_data['ip'] . ')失败：' . json_encode($request_result, JSON_UNESCAPED_UNICODE), 'info');
									return ['code' => 1, 'msg' => '渠道信息更新成功，cmpp信息更新失败'];
								}

							} else {

								return ['code' => 0, 'msg' => '渠道信息更新成功'];
							}

						} catch (\Exception $e) {

							Db::rollback();
							trace("渠道信息更新成功，cmpp信息更新失败" . $e);

							return ['code' => 1, 'msg' => '渠道信息更新成功，cmpp信息更新失败'];
						}

					}
				}

				break;

			}

			break;
		}
	}

	public function DeleteChannel() {
		$data = $this->request->post();

		if (empty($data['channel_id'])) {
			return ['code' => 1, 'msg' => '参数不存在'];
		}

		$channel = ChannelModel::where('channel_id', $data['channel_id'])->find();

		// $channel['level'] =
		// p_id',
		$relate_id = session('relate_id');

		$cantdel = false;
		$did     = $data['channel_id'];

		//找要删除的渠道上级是不是自己
		for ($i = 1; $i < $channel['level']; $i++) {

			$pid = ChannelModel::where('channel_id', $did)->value('p_id');

			if ($pid == $relate_id) {
				$cantdel = true;
				break;
			}
		}

		if ($cantdel) {
			if (ChannelModel::where('channel_id', $data['channel_id'])->update(['delete_time' => date('Y-m-d H:i:s')])) {

				trace(session('username') . '删除渠道' . $data['channel_id']);

				return json(['code' => 200, 'message' => '删除成功']);
			}

		}

		return json(['code' => 0, 'message' => '删除失败']);
	}
}
